﻿using CommonClass;
using I_Authorization.Domains.RBAC;
using I_Authorization.Infrastructure;
using I_Authorization.Infrastructure.Interface;
using I_Authorization.Read.API.Application.Commands.Menu;
using MediatR;

namespace I_Authorization.Read.API.Application.CommandHandlers.Menu
{
    public class MenuReadCommandHandler : IRequestHandler<MenuReadCommand, List<MenuTreeData<MenuList>>>
    {
        private readonly IMenuRepository _menuRepository;

        public MenuReadCommandHandler(IMenuRepository menuRepository)
        {
            _menuRepository = menuRepository;
        }

        public async Task<List<MenuTreeData<MenuList>>> Handle(MenuReadCommand request, CancellationToken cancellationToken)
        {
            var menuList = await _menuRepository.GetAsync(x => x.ParentId.Equals(request.ParentId));
            var menuTreeData = new List<MenuTreeData<MenuList>>();
            foreach (var item in menuList)
            {
                menuTreeData.Add(new MenuTreeData<MenuList>
                {
                    Id = item.Id,
                    MenuName = item.MenuName,
                    MenuURL = item.URL,
                    Children = await _menuRepository.GetAsync(a => item.Id.Equals(a.ParentId)),
                });
            }
            return menuTreeData;
        }
    }
}
